package cn.com.header.zbpk.sys.controller;

import cn.com.header.core.support.web.JsonViewData;
import cn.com.header.core.support.web.ResultCode;
import cn.com.header.core.util.*;
import cn.com.header.zbpk.sys.entity.Attachment;
import cn.com.header.zbpk.sys.service.IAttachService;
import cn.com.header.zbpk.web.CommonController;
import com.google.common.collect.Maps;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigInteger;

import java.util.Map;

/**
 * 附件管理
 *
 * @author Yuanyifeng
 * @date 2017-11-22
 * @time 20:22
 */
@Controller
@RequestMapping("sys/attach")
public class AttachController extends CommonController {
    @Value("${system.ip.url}")
    private String systemIpUrl;
    @Autowired
    private IAttachService iAttachService;

    /**
     * 上传附件
     */
    @RequestMapping("upload")
    public @ResponseBody
    void upload(MultipartFile file, Attachment attach, HttpServletResponse response, HttpServletRequest request) throws IOException {
        attach.setFileName(file.getOriginalFilename());
        //由于客户端使用flash组件上传，这里获取的文件类型不正确。
        //文件类型的获取放到iAttachService.writeAndSave()方法中设置
        //attach.setFileType(file.getContentType()); //application/octet-stream
        attach.setCreaterId(getCurrentUserId());
        attach.setFileSize(file.getSize());
        iAttachService.writeAndSave(attach, file.getInputStream(), request);
        //为了防止IE提示下载，不能直接返回attach对象，而应该以html的形式输出json字符串
    }

    /**
     * excel下载
     * @param response
     * @param path
     */
    @RequestMapping("excelTemp/download")
    public  void downloadDepart(HttpServletResponse response,String path){
        ExportUtil eu = new ExportUtil(path,"数据模板.xls","学生账号批量导入");
        eu.downloadFile(response);
    }
    /**
     * 下载附件
     */
    @RequestMapping("download")
    public void download(Long id, Model model, HttpServletResponse response, HttpServletRequest request) {
        if (id == null) return;
        Attachment attach = iAttachService.loadAttach(id);
        try {
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename=" +
                    new String((attach.getFileName()).getBytes("GB2312"), "iso8859-1"));
            InputStream input = iAttachService.getFileInputStream(id, request);
            IOUtils.copy(input, response.getOutputStream());
            input.close();
            response.flushBuffer();
            response.getOutputStream().close();
        } catch (Exception e) {
            e.printStackTrace();
        /*	this.outputHtml("下载附件发生意外，请返回", response);
            AppUtils.logError("下载附件出错：%s", e.getMessage());*/
        }
    }

    /**
     * 打开显示图片文件
     */
    @RequestMapping("view-image")
    public void viewImage(Long id, String c, HttpServletResponse response, HttpServletRequest request) {
/*		前端验证码c产生js代码
getAttachCode : function(imgId) {
			if (!imgId)
				return null;
			imgId = imgId * (imgId % 10) + "";
			var code = "";
			for (var i = 0; i < imgId.length; i++) {
				var c = lu.int(imgId.charAt(i));
				code += c * (c + 1)
			}
			if (code.length > 8)
				code = code.substring(code.length - 8);
			return code
		},*/
        response.setContentType("image/jpeg");
        if (id == null) return;
        if (!codeMatches(id, c)) {
            /*logger.debug("查看图片时验证码有误：{}", c);*/
            return;
        }
        Attachment attach = iAttachService.loadAttach(id);
        if (attach == null) return;
        if (StringUtils.contains(attach.getFileType(), "image")) {
            response.setContentType(attach.getFileType());
        }
        try {
            InputStream input = iAttachService.getFileInputStream(id, request);
            IOUtils.copy(input, response.getOutputStream());
            input.close();
            response.getOutputStream().close();
        } catch (Exception e) {
            response.reset();
        }
    }

    private boolean codeMatches(Long imgId, String code) {
        if (imgId == null || code == null) return false;
        String tmp = BigInteger.valueOf(imgId).multiply(BigInteger.valueOf(imgId % 10)).toString();//imgId*(imgId%10)
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < tmp.length(); i++) {
            int c = LangUtils.parseInt(tmp.substring(i, i + 1));
            sb.append(c * (c + 1));
        }
        if (sb.length() > 8) sb.delete(0, sb.length() - 8);
        return sb.toString().equals(code);
    }

    /**
     * 产生img验证码
     *
     * @param imgId
     * @return
     */
    private String generateImgCode(Long imgId) {
        String tmp = BigInteger.valueOf(imgId).multiply(BigInteger.valueOf(imgId % 10)).toString();//imgId*(imgId%10)
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < tmp.length(); i++) {
            int c = LangUtils.parseInt(tmp.substring(i, i + 1));
            sb.append(c * (c + 1));
        }
        if (sb.length() > 8) sb.delete(0, sb.length() - 8);
        return sb.toString();
    }

    /**
     * test
     */
    @RequestMapping("index")
    public String index(HttpServletRequest request) throws IOException {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        request.setAttribute("name", "yyf");
        return "index";
    }

    /**
     * webSocket测试
     */
    @RequestMapping("webSocket")
    public String webSocket(){
        return "web-socket";
    }


    /**
     * 异步上传图片
     *
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("ajaxUploadImg")
    @ResponseBody
    public JsonViewData ajaxUploadImg(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) throws IOException {
        if (file.isEmpty()) {
            return setJsonViewData(ResultCode.PARAM_ERROR, "请提供需要上传的文件！！！");
        }
        Attachment attach = new Attachment();
        attach.setType(Attachment.Type.QUESTION_IMG);
        attach.setFileName(file.getOriginalFilename());
        attach.setCreaterId(getCurrentUserId());
        attach.setFileSize(file.getSize());
        iAttachService.writeAndSave(attach, file.getInputStream(), request);
        Long imgId = attach.getId();
        String ipUrl = systemIpUrl;
        if (ipUrl.endsWith("/")) {
            ipUrl = ipUrl.substring(0, ipUrl.length() - 1);
        }
        String path = ipUrl + request.getContextPath() + "/sys/attach/view-image?id=" + imgId + "&c=" + generateImgCode(imgId);
        Map<String, Object> map = Maps.newHashMap();
        map.put("imgPath", path);
        return setJsonViewData(map);
    }
    /**
     * 模拟发送数据
     */
    @RequestMapping(value = "testData")
    @ResponseBody
    public String testData(HttpServletResponse response, Long id) {
        JSONObject obj = new JSONObject();
        obj.put("name", "yyf");
        obj.put("id", id);
        obj.put("year", "10");
        return obj.toString();
    }


}
